#include <47func.h>
int main(int argc, char *argv[])
{
    // ./0_server_udp 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);//SOCK_DGRAM 意味着传输层是udp
    // 设置服务端的地址 本机的地址
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    serverAddr.sin_port = htons(atoi(argv[2]));
    // bind操作
    int ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"bind");

    //recvfrom 获取所有收到的消息的第一个消息，取出该消息发送方的ip和端口
    char buf[1024] = {0};
    struct sockaddr_in clientAddr;
    socklen_t clientAddrSize = sizeof(clientAddr);
    ssize_t sret = recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&clientAddr, &clientAddrSize);
    ERROR_CHECK(sret,-1,"recvfrom");
    printf("buf = %s\n", buf);
    printf("client ip = %s, port = %d\n",
           inet_ntoa(clientAddr.sin_addr),
           ntohs(clientAddr.sin_port));
    // 在服务端recvfrom完成之后，服务端可以执行sendto了
    sret = sendto(sockfd,"hello",5,0,(struct sockaddr *)&clientAddr, clientAddrSize);
    ERROR_CHECK(sret,-1,"sendto");
    sret = sendto(sockfd,"world",5,0,(struct sockaddr *)&clientAddr, clientAddrSize);
    ERROR_CHECK(sret,-1,"sendto");
    close(sockfd);
    return 0;
}

